package com.ld.security.auth.shiro.anno.aop;

import com.ld.security.auth.shiro.anno.PermissionKey;
import com.ld.security.auth.shiro.util.LoginUtil;
import com.ld.security.common.core.exception.ApiException;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Order(5)
public class PermissionAop {



    @Pointcut("@annotation(com.ld.security.auth.shiro.anno.PermissionKey)")
    public void aop() {

    }

   @Around("aop()")
    public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
       PermissionKey permissionKey =  AnnotationUtils.findAnnotation(method, PermissionKey.class);
       boolean b = SecurityUtils.getSubject().isPermitted(permissionKey.value());

       if(!b){
           if(!LoginUtil.isAdmin()){
               ApiException.throw401("权限不足"+permissionKey.label());
           }
       }

        return pjp.proceed();
    }



}
